import re
from typing import Optional
from pydantic import field_validator
from sqlalchemy import Column, TEXT
from sqlmodel import Field, JSON
from sqlmodel import SQLModel
from core.exception.errors import ValidateError
from models.base_model import BaseModel


class AdminUserBase(SQLModel):
    username: str = Field(nullable=False, max_length=32, unique=True, description="用户名称")
    email: Optional[str] = Field(nullable=True, default=None, description="邮箱")
    is_active: bool = Field(default=True, description="是否激活")
    avatar: Optional[str] = Field(nullable=True, default=None, max_length=256, description="用户头像")
    group_id: Optional[int] = Field(nullable=True, description="用户分组ID")

    @field_validator('username')
    def validator_username(cls, v):
        if not re.match(r"^[a-zA-z]\w{1,9}", v):
            raise ValidateError(msg="用户名格式不正确")
        return v


class AdminListDetail(AdminUserBase):
    group_name: Optional[int] = Field(nullable=True, description="用户分组名称")


class AdminUser(BaseModel, AdminUserBase, table=True):
    """
    后台管理员表
    """
    __tablename__ = 't_admin_user'
    hashed_password: str = Field(nullable=False, description="密码hash")
    username: str = Field(nullable=False, max_length=32, unique=True, description="用户名称")
    email: Optional[str] = Field(nullable=True, description="邮箱")
    is_active: bool = Field(default=True, description="是否激活")
    avatar: Optional[str] = Field(nullable=True, max_length=256, description="用户头像")
    group_id: Optional[int] = Field(nullable=True, description="用户分组ID")

    @field_validator('username')
    def validator_username(cls, v):
        if not re.match(r"^[a-zA-z]\w{1,9}", v):
            raise ValidateError(msg="用户名格式不正确")
        return v


class ManageGroupBase(SQLModel):
    """
    管理员分组
    """
    group_name: str = Field(nullable=False, min_length=1, max_length=32, unique=True, description="分组名称")
    roles: Optional[list] = Field(default=[], sa_column=Column(JSON), description="分组权限列表")


class ManageGroup(BaseModel, ManageGroupBase, table=True):
    """
    后台管理员表
    """
    __tablename__ = 't_manage_group'

